package com.zl.learning.thread;

import java.util.concurrent.*;

public class TestFutureTask {
    public static class TestFutureTask1 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            FutureTask<String> ft = new FutureTask<String>(() -> {
                TimeUnit.SECONDS.sleep(1);
                return "zhangsan";
            });
            new Thread(ft).start();
            System.out.println("thread start");
            String val = ft.get();
            System.out.println(val);
        }
    }

    public static class TestFutureTask2 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            ExecutorService service = Executors.newCachedThreadPool();
            Future<String> future = service.submit(() -> {
                TimeUnit.SECONDS.sleep(1);
                return "zhangsan";
            });
            System.out.println("thread start");
            String val = future.get();
            service.shutdown();
            System.out.println(val);
        }
    }

    public static class TestFutureTask3 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            ExecutorService service = Executors.newCachedThreadPool();
            CompletionService<String> completionService = new ExecutorCompletionService<>(service);
            Future<String> future = completionService.submit(() -> {
                TimeUnit.SECONDS.sleep(1);
                return "zhangsan";
            });
            System.out.println("thread start");
            String val = future.get();
            service.shutdown();
            System.out.println(val);
        }
    }
}
